//
//  LYPictureFirstVC.m
//  LYCustomTransitionDemo
//
//  Created by liyang on 2017/12/5.
//  Copyright © 2017年 liyang. All rights reserved.
//
#import "LYPictureBrowseViewController.h"
#import "QAChooseToSendVC.h"
#import "QAChatViewController.h"
#import "QALookPhotoVC.h"
#import "QAGroupInviteVC.h"
#import "QAAddressBookDetailVC.h"

#import "LFPhotoEditingController.h"
#import "MOVideoCollectionView.h"
#import "LYPictureBrowserCell.h"
/** 自定义的视频cell */
#import "MOLYPicAVPlayerCollectionViewCell.h"

#import "MOAlbumDetailItemModel.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "MOGestureView.h"
#import "GGProgressView.h"
#import "MOAlertView.h"
#import "QARtcEngine.h"
#import "MOPhotoLibraryManager.h"
#import "ICVideoManager.h"
#import "QAAPI+User.h"
#import "QAWebViewController.h"
#import "QAIMDatabase.h"
#import "QAConversation+Util.h"
#import "QAAddressBookDetailVC.h"
#import "QABaseNavigationController.h"
#import "ICFileTool.h"
#import "ICMediaManager.h"
#define IPHONE_W MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)
#define IPHONE_H MAX([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)
@interface LYPictureBrowseViewController ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UICollectionViewDelegate, LYPictureBrowserCellDelegate, LFPhotoEditingControllerDelegate,MOGestureViewDelegate> {
    
    GGProgressView *_progressView;
    UILabel *_labCountDown;
    
    
    NSInteger _offsetItemCount;
    CGFloat currentWidth;
    CGFloat currentHeight;
}

@property (nonatomic, strong) MOVideoCollectionView *collectionView;
@property (nonatomic, assign) CGPoint transitionImgViewCenter;
@property (nonatomic, strong) UIImageView         *imgView;
@property (nonatomic, strong) MOGestureView *gestureView;

@property (nonatomic,strong) UITapGestureRecognizer *singleTap;
@property (nonatomic,strong) UITapGestureRecognizer *doubleTap;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;

@property (nonatomic, strong) UIImage *currentImage;
@property (nonatomic, assign) NSInteger currentImageIndex;
@property (nonatomic, assign) NSInteger centerCellIndex;

@property (nonatomic, weak) MOAlerter *sheetView;
@property (nonatomic, copy) NSString *qrcodeString;

@property (nonatomic,assign) UIDeviceOrientation orientation;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, assign) BOOL haveQR;
@property (nonatomic, assign) BOOL directionChange;
@property (nonatomic, assign) BOOL isDirectVedio; //直接点击视频进入
/// 当前视频cell
@property(nonatomic, strong) MOLYPicAVPlayerCollectionViewCell *currentVideoCell;

@property (nonatomic, strong) NSTimer *timerCountDown;
@property (nonatomic, assign) BOOL animating;

@end

@implementation LYPictureBrowseViewController

#pragma mark - Life Cycle


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    if (self.currentVideoCell) {
        if (self.currentVideoCell.task) {
            [self.currentVideoCell.task cancel];
        }
    }

   [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    self.fd_prefersNavigationBarHidden = NO;
//    self.hidesNavigationBar = NO;
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
   [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self pauseAndStart];
    [self.sheetView hide];
    
    if (_progressView) {
         _progressView.alpha = 0;
    }
//    [self hideShowView];
    

    [self becomePortrait];
   
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_timerCountDown invalidate];
    _timerCountDown = nil;

    //浮窗状态隐藏
    [SuspensionEntrance shared].hidden = false;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   self.fd_prefersNavigationBarHidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:NO];
   
     if (_progressView) {
          _progressView.alpha = 1;
     }
    if([[UIScreen mainScreen] bounds].size.height>[[UIScreen mainScreen] bounds].size.width){
           currentWidth = IPHONE_W;
           currentHeight = IPHONE_H;
       }else{
           currentWidth = IPHONE_H;
           currentHeight = IPHONE_W;
       }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startVideoPlay:) name:@"startVideoPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseVideoPlay:) name:@"pauseVideoPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseAndStartRound) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:@"applicationDidBecomeActive" object:nil];
    [QARtcEngine addStartCallNotificationWithObserver:self selector:@selector(pauseVideoPlay:)];
    [QARtcEngine addEndCallNotificationWithObserver:self selector:@selector(startVideoPlay:)];
    
    WCICache.rotateStyle = 4;
    [[[UIApplication sharedApplication] delegate] application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];

    //浮窗状态隐藏
    [SuspensionEntrance shared].hidden = true;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.gestureView = [[MOGestureView alloc]init];
    self.gestureView.delegate = self;
    [self.view addSubview:self.gestureView];
    [self.gestureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_offset(0);
    }];
//    self.hidesNavigationBar = YES;
    self.view.backgroundColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationView.backgroundColor = nil;
    
    if([[UIScreen mainScreen] bounds].size.height>[[UIScreen mainScreen] bounds].size.width){
        currentWidth = IPHONE_W;
        currentHeight = IPHONE_H;
    }else{
        currentWidth = IPHONE_H;
        currentHeight = IPHONE_W;
    }
    
    [self.gestureView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(50);
        make.bottom.mas_equalTo(0);
    }];
    
    self.currentImageIndex = self.animatedTransition.transitionParameter.transitionImgIndex;
    self.centerCellIndex = self.animatedTransition.transitionParameter.transitionImgIndex;
    id tempData = self.msgArray[self.currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *model = tempData;
        NSInteger replyType = 0;
        
        if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
            replyType = replyModel.sendType;
        }

        if (model.contentType == MPMessageContentTypeVideo || replyType == MPMessageContentTypeVideo) {
            self.isDirectVedio = YES;
        }else{
            self.isDirectVedio = NO;
        }
    }else{
        MOAlbumDetailItemModel *model = tempData;
        if (model.type == MOSecretAlbumItemTypeVid ) {
            self.isDirectVedio = YES;
        }else{
            self.isDirectVedio = NO;
        }
    }
    
    [self.gestureView addGestureRecognizer:self.longPress];
    
    self.singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popVC)];
    self.singleTap.numberOfTapsRequired = 1;
    self.singleTap.delaysTouchesBegan = YES;
    //只能有一个手势存在
    [self.singleTap requireGestureRecognizerToFail:self.doubleTap];
    [self.gestureView addGestureRecognizer:self.singleTap];

    [self.gestureView addGestureRecognizer:self.doubleTap];
    
    _currentImage = self.animatedTransition.transitionParameter.transitionImage;
    _currentImageIndex = self.animatedTransition.transitionParameter.transitionImgIndex;
    [self configLookAllImg];

    [self configWhisperBottom];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recallMsg:) name:@"recallMsg" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_bothRecallMsg:) name:@"noti_bothRecallMsg" object:nil];

}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)applicationDidBecomeActive {
    [self endGestureWithScale:1];
}

#pragma mark -

- (void)becomePortrait{
    WCICache.rotateStyle = 0;
    
    [[[UIApplication sharedApplication] delegate] application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
    //设置屏幕的转向为竖屏
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}
- (void)allowAllDirection{
    WCICache.rotateStyle = 4;
    
    [[[UIApplication sharedApplication] delegate] application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
    
}


- (void)popVC{
    if (_timerCountDown) {
        [_timerCountDown invalidate];
        _timerCountDown = nil;
    }
    id tempData = self.msgArray[self.currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        [self popSecure];
    }else{
        MOAlbumDetailItemModel *model = tempData;
        if (model.browserType == MOAlbumBrowserTypeFile||model.browserType == MOAlbumBrowserTypeFileCollection) {
            [self popToIntoVC];
        }else{
            [self popSecure];
        }
    }
   
}
- (void)popSecure{
    if (currentWidth<currentHeight) {
        [self porPop];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(porPop) withObject:nil afterDelay:0.5];
        
    }
}
- (void)popToIntoVC{
    if (currentWidth<currentHeight) {
        [self popToLast];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(popToLast) withObject:nil afterDelay:0.5];
    }
}
- (void)popToLast{
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index -2)] animated:YES];
}
- (void)porPop{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)porPopNoAnimate{
    [self.navigationController popViewControllerAnimated:NO];
}
#pragma mark - config views

//查看所有图片
- (void)configLookAllImg {
    if (self.hidenShowAllPhoto) {
        return;
    }
    
    if ([self.totleCountDown integerValue] > 0) {
        return;
    }
    
    if (([self.comeController isKindOfClass:[QAChatViewController class]] ||

         [self.comeController isKindOfClass:[QALookPhotoVC class]])&& !self.hiddenAllImg) {

        UIButton *lookAllImgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [lookAllImgButton addTarget:self action:@selector(lookAllImgButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [lookAllImgButton setImage:[UIImage imageNamed:@"img_icon_look_allI_mage"] forState:0];
        [self.gestureView addSubview:lookAllImgButton];
        [lookAllImgButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(40);
            make.right.mas_equalTo(-20);
        }];
    }
}

- (void)showPopUpView {
    if ([self.countDown integerValue] > 0) {
        return;
    }
    WeakSelf(ws);
    
    id tempData = self.msgArray[_currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *message = (QAMessage *)self.msgArray[_currentImageIndex];
        BOOL isImage = NO;
        if (message.contentType == MPMessageContentTypeNewReply || message.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
            if (replyModel.sendType == 1022) {
                isImage = YES;
            }
        }
        
        if (message.contentType == MPMessageContentTypePicture || message.contentType == MPMessageContentTypeNewPicture || isImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh}];
                //2. 扫描获取的特征组
                NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:weakSelf.currentImage.CGImage]];
                //3. 获取扫描结果
                if (features.count > 0) {
                    CIQRCodeFeature *feature = [features objectAtIndex:0];
                    weakSelf.qrcodeString = feature.messageString;
                    NSArray * tempArray = @[(@"转发给朋友"),(@"收藏"),(@"保存图片"),(@"编辑"),(@"识别图中二维码"),(@"定位到聊天位置")];
                    self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                        [weakSelf.sheetView hide];
                        if (index == 0) {
                            [weakSelf sendImageToFriend];
                        } else if (index == 1){
                            [weakSelf collectionImage];
                        } else if (index == 2){
                            [weakSelf saveImage];
                        } else if (index == 3){
                            [weakSelf editAction];
                        } else if (index == 4){
                            [weakSelf qrcode];
                        }else if(index == 5) {
                            [weakSelf jumpToMsg:message];
                        }
                    } touchHide:YES];
                    self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                    self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
                }else{
                    NSArray * tempArray = @[(@"转发给朋友"),(@"收藏"),(@"保存图片"),(@"编辑"),(@"定位到聊天位置")];
                    self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                        [weakSelf.sheetView hide];
                        if (index == 0) {
                            [weakSelf sendImageToFriend];
                        } else if (index == 1){
                            [weakSelf collectionImage];
                        } else if (index == 2){
                            [weakSelf saveImage];
                        } else if (index == 3){
                            [weakSelf editAction];
                        } else if (index == 4) {
                            [weakSelf jumpToMsg:message];
                        }
                    } touchHide:YES];
                    self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                    self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
                }
            });
        }else{
            NSArray * tempArray = @[(@"转发给朋友"),(@"收藏"),(@"保存视频"),(@"定位到聊天位置")];
            self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                [weakSelf.sheetView hide];
                if (index == 0) {
                    [weakSelf sendImageToFriend];
                } else if (index == 1){
                    [weakSelf collectionImage];
                } else if (index == 2){
                    [weakSelf saveImage];
                } else if (index == 3) {
                    [weakSelf jumpToMsg:message];
                }

            } touchHide:YES];
            self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
            self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
        }
    }else{

        MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)self.msgArray[_currentImageIndex];
        if (model.browserType == MOAlbumBrowserTypeCollection || model.browserType == MOAlbumBrowserTypeFileCollection) {
            if (model.type == MOSecretAlbumItemTypePic) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh}];
                    //2. 扫描获取的特征组
                    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:weakSelf.currentImage.CGImage]];
                    //3. 获取扫描结果
                    if (features.count > 0) {
                        CIQRCodeFeature *feature = [features objectAtIndex:0];
                        weakSelf.qrcodeString = feature.messageString;
                        NSArray * tempArray = @[(@"转发给朋友"),(@"保存图片"),(@"编辑"),(@"识别图中二维码"),self.isTopMsg ? (@"定位到聊天位置") : @""];
                        self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                            [weakSelf.sheetView hide];
                            if (index == 0) {
                                [weakSelf sendImageToFriend];
                            } else if (index == 1){
                                [weakSelf saveImage];
                            } else if (index == 2){
                                [weakSelf editAction];
                            } else if (index == 3){
                                [weakSelf qrcode];
                            }else if (index == 4) {
                                [weakSelf jumpToMsg:weakSelf.topMsg];
                            }
                        } touchHide:YES];
                        self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                        self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
                    }else{
                        NSArray * tempArray = @[(@"转发给朋友"),(@"保存图片"),(@"编辑"),self.isTopMsg ? (@"定位到聊天位置") : @""];
                        self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                            [weakSelf.sheetView hide];
                            if (index == 0) {
                                [weakSelf sendImageToFriend];
                            } else if (index == 1){
                                [weakSelf saveImage];
                            } else if (index == 2){
                                [weakSelf editAction];
                            }else if (index == 3) {
                                [weakSelf jumpToMsg:weakSelf.topMsg];
                            }
                        } touchHide:YES];
                        self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                        self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
                    }
                });
            }else{
                NSArray * tempArray = @[(@"转发给朋友"),(@"保存视频"),self.isTopMsg ? (@"定位到聊天位置") : @""];
                self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                    [weakSelf.sheetView hide];
                    if (index == 0) {
                        [weakSelf sendImageToFriend];
                    } else if (index == 1){
                        [weakSelf saveImage];
                    }else if (index == 2) {
                        [weakSelf jumpToMsg:weakSelf.topMsg];
                    }
                } touchHide:YES];
                self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
            }
        }else{
            if (model.type == MOSecretAlbumItemTypePic) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh}];
                    //2. 扫描获取的特征组
                    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:weakSelf.currentImage.CGImage]];
                    //3. 获取扫描结果
                    if (features.count > 0) {
                        CIQRCodeFeature *feature = [features objectAtIndex:0];
                        weakSelf.qrcodeString = feature.messageString;
                        NSArray * tempArray = @[(@"转发给朋友"),(@"收藏"),(@"保存图片"),(@"编辑"),(@"识别图中二维码"),self.isTopMsg ? (@"定位到聊天位置") : @""];
                        self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                            [weakSelf.sheetView hide];
                            if (index == 0) {
                                [weakSelf sendImageToFriend];
                            } else if (index == 1){
                                [weakSelf collectionImage];
                            } else if (index == 2){
                                [weakSelf saveImage];
                            } else if (index == 3){
                                [weakSelf editAction];
                            } else if (index == 4){
                                [weakSelf qrcode];
                            }else if (index == 5) {
                                [weakSelf jumpToMsg:weakSelf.topMsg];
                            }
                        } touchHide:YES];
                        self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                        self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
                    }else{
                        NSArray * tempArray = @[(@"转发给朋友"),(@"收藏"),(@"保存图片"),(@"编辑"),self.isTopMsg ? (@"定位到聊天位置") : @""];
                        self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                            [weakSelf.sheetView hide];
                            if (index == 0) {
                                [weakSelf sendImageToFriend];
                            } else if (index == 1){
                                [weakSelf collectionImage];
                            } else if (index == 2){
                                [weakSelf saveImage];
                            } else if (index == 3){
                                [weakSelf editAction];
                            }else if (index == 4) {
                                [weakSelf jumpToMsg:weakSelf.topMsg];
                            }
                        } touchHide:YES];
                        self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                        self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
                    }
                });
            }else{
                NSArray * tempArray = @[(@"转发给朋友"),(@"收藏"),(@"保存视频"),self.isTopMsg ? (@"定位到聊天位置") : @""];
                self.sheetView = [MOAlerter alertSheetStyleWithTitles:tempArray title:nil message:nil cancelTitle:(@"取消") selectedAction:^(MOAlerter *alerter, NSInteger index) {
                    [weakSelf.sheetView hide];
                    if (index == 0) {
                        [weakSelf sendImageToFriend];
                    } else if (index == 1){
                        [weakSelf collectionImage];
                    } else if (index == 2){
                        [weakSelf saveImage];
                    }else if (index == 3) {
                        [weakSelf jumpToMsg:weakSelf.topMsg];
                    }
                } touchHide:YES];
                self.sheetView.hidesAlerterWhenOrientationDidChang = YES;
                self.sheetView.supportedInterfaceOrientations = UIInterfaceOrientationMaskAll;
            }
        }
    }
    
}

- (void)configWhisperBottom {
    id tempData = self.msgArray[_currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        
        if ([self.countDown integerValue] > 0) {
            WeakSelf(ws);
            _progressView = [[GGProgressView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-20, SCREEN_WIDTH, 20)];
            //设置
            _progressView.progressTintColor = UIColorFromHex(0xF16859);
            _progressView.trackTintColor = UIColorFromHex(0x4C4C4C);
            _progressView.progressViewStyle = GGProgressViewStyleDefault;
            [self.gestureView addSubview:_progressView];
            [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_offset(0);
                make.height.mas_equalTo(20);
                if (WCI_IPHONE_SAFEBOTTOMAREA_HEIGHT>0) {
                    make.bottom.mas_offset(-10);
                }else{
                    make.bottom.mas_offset(0);
                }
            }];
            [_progressView setProgress:[weakSelf.countDown floatValue]/[weakSelf.totleCountDown doubleValue]];
            _labCountDown = [[UILabel alloc] initWithFrame:CGRectZero];
            _labCountDown.textColor = [UIColor whiteColor];
            _labCountDown.text = [self configBurnTimeShowWithCountDownTime:[NSString stringWithFormat:@"%@",self.countDown]];
            _labCountDown.textAlignment = NSTextAlignmentCenter;
            _labCountDown.font = [UIFont systemFontOfSize:12];
            [_progressView addSubview:_labCountDown];
            [_labCountDown mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.bottom.mas_offset(0);
            }];
            _timerCountDown = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:_timerCountDown forMode:NSRunLoopCommonModes];
            
        }
    }
}

#pragma mark - Action

//保存图像
- (void)saveImage {
    //    int index = _scrollView.contentOffset.x / _scrollView.bounds.size.width;
     id dataTemp = self.msgArray[self.currentImageIndex];
    if ([dataTemp isKindOfClass:[QAMessage class]]) {
        QAMessage *message = (QAMessage *)dataTemp;
        NSInteger replyType = 0;
        if (message.contentType == MPMessageContentTypeNewReply || message.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
            replyType = replyModel.sendType;
        }

        if (message.contentType == MPMessageContentTypePicture || message.contentType == MPMessageContentTypeNewPicture || replyType == MPMessageContentTypeNewPicture) {
            NSString *lnk = message.lnk;
            if (replyType == MPMessageContentTypeNewPicture) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
                MPParserImageMsg *picMsgModel = [MPParserImageMsg yy_modelWithJSON:replyModel.sendContent];
                lnk = picMsgModel.url;
            }
            [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:lnk] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                        
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {

                [MOPhotoLibraryManager savePhotoWithImage:image andAssetCollectionName:nil withCompletion:^(UIImage * _Nonnull image, NSError * _Nonnull error) {
                    if (error) {
                        WCIToast.showMsg(@"保存图片失败");
                    } else {
                        WCIToast.showMsg(@"保存图片成功");
                    }
                }];

            }];
        }else{
            
            NSString *vidName = message.fileKey.lastPathComponent.stringByDeletingPathExtension;
            if (replyType == 1004) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
                NSDictionary *vidInfo = [NSDictionary dictionaryWithJsonString:replyModel.sendContent];
                vidName = [NSString stringWithFormat:@"%@",[vidInfo objectForKey:@"videoPath"]].lastPathComponent.stringByDeletingPathExtension;
            }
            NSString *path = [[ICVideoManager shareManager] videoPathWithFileName:vidName];
            
            BOOL compatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path);
            if (compatible) {
                UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            }else{
                WCIToast.showMsg(@"保存失败");
            }
        }
    }else{
        MOAlbumDetailItemModel *message = (MOAlbumDetailItemModel *)dataTemp;
        if (message.type == MOSecretAlbumItemTypePic) {
            [MOPhotoLibraryManager savePhotoWithImage:_currentImage andAssetCollectionName:nil withCompletion:^(UIImage * _Nonnull image, NSError * _Nonnull error) {
                if (error) {
                    WCIToast.showMsg(@"保存图片失败");
                } else {
                    WCIToast.showMsg(@"保存图片成功");
                }
            }];

        }else{
            NSString *path = [[ICVideoManager shareManager] videoPathForMP4:message.src];
            
            BOOL compatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path);
            if (compatible) {
                UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            }else{
                WCIToast.showMsg(@"保存失败");
            }
        }
    }
     
}

//转发给朋友
- (void)sendImageToFriend {
    [self pauseAndStart];
    if (currentWidth<currentHeight) {
        [self sendImageToFriendGo];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(sendImageToFriendGo) withObject:nil afterDelay:0.5];
    }
}
- (void)sendImageToFriendGo{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"pauseVideoPlay" object:nil];
    QAChooseToSendVC *chooseVC = [QAChooseToSendVC new];
    
    id dataTemp = self.msgArray[self.currentImageIndex];
    
    
    if ([dataTemp isKindOfClass:[QAMessage class]]) {
        QAMessage *message = self.msgArray[self.currentImageIndex];
        
        MPMessageContentType replyTyep = MPMessageContentTypeNone;
        if (message.contentType == MPMessageContentTypeNewReply || message.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
            replyTyep = replyModel.sendType;
        }
        if (message.contentType == MPMessageContentTypePicture || message.contentType == MPMessageContentTypeNewPicture || replyTyep == MPMessageContentTypeNewPicture) {
            if (replyTyep == MPMessageContentTypeNewPicture) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
                
                chooseVC.comeType = MPChooseToSendFrom_Pic;
                chooseVC.reciveMsg = replyModel.sendContent;
                [QAChooseToSendVC showInVC:self toVC:chooseVC];
                
            } else {
                QAConversation *group = [[QAIMDatabase sharedInstance] getConversationWithGid:message.msgTo];
                BOOL isSender = NO;
                if ([message.msgFrom isEqualToString:WCICache.user.userId]) {
                    isSender = YES;
                }
                QAMessageFrame *messageF = [QAMessageFrame messageFrameFromMessage:message conversation:group myUserId:WCICache.user.userId];
                messageF.someExtData.isShowTime = YES;
                messageF.someExtData.mediaPath = message.fileKey;
                chooseVC.messageF = messageF;
                [QAChooseToSendVC showInVC:self toVC:chooseVC];
            }
        }else{
            NSString *vidInfo = message.receiveMsg;
            
            if (replyTyep == MPMessageContentTypeVideo) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
                vidInfo = replyModel.sendContent;
            }
            NSDictionary *dic = [NSDictionary dictionaryWithJsonString:vidInfo];
            if (dic[@"videoPath"]) {
                chooseVC.comeType = MPChooseToSendFrom_Video;
                chooseVC.reciveMsg = vidInfo;
                [QAChooseToSendVC showInVC:self.comeController toVC:chooseVC];
            }else{
                WCIToast.showMsg(@"发送失败");
            }
        }
        
    } else {
        
        MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)dataTemp;
        if (model.type == MOSecretAlbumItemTypePic) {
            chooseVC.albumModels = @[model];
            [QAChooseToSendVC showInVC:self.comeController toVC:chooseVC];
            //                [self.navigationController pushViewController:chooseVC animated:YES];
        }else{
            NSString *imageString = [model.content yy_modelToJSONObject][@"snapshot"];
            if (imageString.length <= 0) {
                imageString = model.cover_src;
            }
            if (imageString.length) {
                UIImage *image = [[SDImageCache sharedImageCache] imageFromCacheForKey:imageString];
                if (image) {
                    chooseVC.imgT = image;
                    chooseVC.comeType = MPChooseToSendFrom_Video;
                    chooseVC.videoContent = model.content;
                    [QAChooseToSendVC showInVC:self.comeController toVC:chooseVC];
                }else{
                    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageString] options:SDWebImageDownloaderLowPriority progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                        chooseVC.imgT = image;
                        chooseVC.comeType = MPChooseToSendFrom_Video;
                        chooseVC.videoContent = model.content;
                        [QAChooseToSendVC showInVC:self.comeController toVC:chooseVC];
                    }];
                }
            }
        }
    }
}
////收藏图片
- (void)collectionImage {
    
   
    id tempData = _msgArray[_currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *message = (QAMessage *)tempData;
        if (message.contentType == MPMessageContentTypeNewReply || message.contentType == MPMessageContentTypeSingleReply) {
            NSMutableDictionary *dicPara = [NSMutableDictionary new];
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:message.receiveMsg];
            [dicPara setObject:@(replyModel.senderId) forKey:@"senderId"];
            [dicPara setObject:replyModel.sendContent  forKey:@"content"];
            [dicPara setObject:@(replyModel.sendType) forKey:@"type"];
            NSDictionary *dic = [NSDictionary dictionaryWithJsonString:replyModel.sendContent];
            if ((replyModel.sendType == 1022 && dic[@"url"]) || (replyModel.sendType == 1004 && dic[@"videoPath"])) {
                __weak typeof (self) weakSelf = self;
                [[[self.api makeParameters:dicPara] makeSuccessHandler:^(QAResponseModel *response) {
                    
                    WCIToast.showMsg(@"收藏成功");
                }] addCollection];
            }else{
                WCIToast.showMsg(@"收藏失败");
            }
        } else {
            NSMutableDictionary *dicPara = [NSMutableDictionary new];

            [dicPara setObject:@([message.msgFrom integerValue]) forKey:@"senderId"];
            [dicPara setObject:message.receiveMsg  forKey:@"content"];
            [dicPara setObject:@(message.contentType) forKey:@"type"];
            NSDictionary *dic = [NSDictionary dictionaryWithJsonString:message.receiveMsg];
            if ((message.contentType == MPMessageContentTypeVideo && dic[@"videoPath"]) || ((message.contentType == MPMessageContentTypePicture || message.contentType == MPMessageContentTypeNewPicture) && dic[@"url"])) {
                
                [[[self.api makeParameters:dicPara] makeSuccessHandler:^(QAResponseModel *response) {
                    WCIToast.showMsg(@"收藏成功");
                }] addCollection];
            }else{
                WCIToast.showMsg(@"收藏失败");
            }
        }

    }else{
        MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)tempData;
        NSMutableDictionary *dicPara = [NSMutableDictionary new];

         [dicPara setObject:@([model.senderId integerValue]) forKey:@"senderId"];
          
         if (model.type == MOSecretAlbumItemTypePic) {
                [dicPara setObject:model.src  forKey:@"content"];
         } else {
                NSDictionary *dicMsg = @{@"duration":@(model.video_len),
                                         @"snapshot":model.cover_src,
                                         @"videoPath":model.src
                                         };

                [dicPara setObject:[dicMsg jsonString]  forKey:@"content"];
         }
        if (model.type == MOSecretAlbumItemTypePic) {
            [dicPara setObject:@(1022) forKey:@"type"];
        } else if (model.type == MOSecretAlbumItemTypeVid) {
            [dicPara setObject:@(1004) forKey:@"type"];
        }
        [[[self.api makeParameters:dicPara] makeSuccessHandler:^(QAResponseModel *response) {
            WCIToast.showMsg(@"收藏成功");
        }] addCollection];
    }
}

/**
 编辑
 */
- (void)editAction{
   

    id tempData = _msgArray[_currentImageIndex];
    
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *  message = (QAMessage *)tempData;
        LYPictureBrowseSouceModel *model = _dataSouceArray[_currentImageIndex];

        LFPhotoEditingController *lfPhotoEditVC = [[LFPhotoEditingController alloc] init];
        lfPhotoEditVC.delegate = self;
        lfPhotoEditVC.isEditInPicture = YES;
        lfPhotoEditVC.message = message;
        lfPhotoEditVC.model = model;
        
            
        lfPhotoEditVC.editImage = self.currentImage;
        [self.navigationController pushViewController:lfPhotoEditVC animated:NO];
    }else{
        MOAlbumDetailItemModel *message = (MOAlbumDetailItemModel *)tempData;
        QAMessage * icMessage = [[QAMessage alloc]init];
        icMessage.msgFrom = message.senderId;
        icMessage.receiveMsg = message.src;
        
        LYPictureBrowseSouceModel *model = _dataSouceArray[_currentImageIndex];
           
        LFPhotoEditingController *lfPhotoEditVC = [[LFPhotoEditingController alloc] init];
        lfPhotoEditVC.delegate = self;
        lfPhotoEditVC.isEditInPicture = YES;
        lfPhotoEditVC.message = icMessage;
        lfPhotoEditVC.model = model;
        lfPhotoEditVC.editImage = self.currentImage;
        [self.navigationController pushViewController:lfPhotoEditVC animated:NO];
    }
}

/**
 识别图中二维码
 */
- (void)qrcode{
    if (currentWidth<currentHeight) {
        [self qrcodeGo];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(qrcodeGo) withObject:nil afterDelay:0.5];
    }
}

- (void)qrcodeGo{
    
    NSURL *url = [NSURL URLWithString:_qrcodeString];
    if (([url.absoluteString containsString:@"subscription/hqr"] || [url.absoluteString containsString:@"group/hgqr"]) || [url.query containsString:@"type=402&data="]) {
        NSString *type = @"";
        NSString *jumpUrlStr = @"" ;
        NSString *serviceId = @"";
        NSArray *resultArr = [[url query] componentsSeparatedByString:@"&"];
        for (NSString *subResult in resultArr) {
            if (subResult.length > 5 && [subResult hasPrefix:@"type="]) {
                type = [subResult substringFromIndex:5];
            }
            
            if (subResult.length > 5 && [subResult hasPrefix:@"data="]) {
                jumpUrlStr = [subResult substringFromIndex:5];
                jumpUrlStr = [jumpUrlStr stringByRemovingPercentEncoding];
            }
            if (subResult.length > 5 && [subResult hasPrefix:@"service="]) {
                serviceId = [subResult substringFromIndex:@"service=".length];
                serviceId = [serviceId stringByRemovingPercentEncoding];
            }
        }
        
        if ([type isEqualToString:@"402"]) {
            if (![WCICache.loginServiceId isEqualToString:serviceId])
            {
                [MOAlerter alertWithMessage:@"不属于同一个服务器，无法操作" confirmTitle:@"好的" touchHide:NO];
                return;
            }

            if ([jumpUrlStr containsString:@"subscription/hqr"] || [jumpUrlStr containsString:@"group/hgqr"]) {
                WeakSelf(ws);
                
                NSMutableDictionary *dicPara = [NSMutableDictionary new];
                [dicPara setObject:WCICache.accessToken forKey:@"tokenId"];
                [[[[[QAAPI.new makeParameters:dicPara] makeUrl:jumpUrlStr] makeSuccessHandler:^(QAResponseModel *response) {
                    NSDictionary *dic = (NSDictionary *)response.data;
                    
                    if ([jumpUrlStr containsString:@"group/hgqr"]) {
                        NSString *stringID = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
                        
                        QAUserInfoModel *myUserInfo = WCICache.user;
                        QAConversation * group = [[QAIMDatabase sharedInstance] getConversationWithGid:stringID];
                        BOOL hasDb = group != nil;
                        if (!group) {
                            group = [QAConversation conversationWithType:MPConversationTypeGroup gid:stringID];
                            group.gName = [dic objectForKey:@"groupname"];
                            group.masterID = [NSString stringWithFormat:@"%@",dic[@"owner"]];
                        }
                        QAConversation *serviceModel = [QAConversation yy_modelWithJSON:dic];
                        [group replaceFromService:serviceModel];

                        if ([group.valid isEqualToString:@"1"]) {
                            if (hasDb) {
                                [[QAIMDatabase sharedInstance] transactionupdateGroupWithNetArray:@[group]];
                            } else {
                                [[QAIMDatabase sharedInstance] transactionInsertConversationArray:@[group]];
                            }
                            QAChatViewController *chatVC = [[QAChatViewController alloc]init];
                            chatVC.conversation = group;
                            [QAModuleService pushToChatVc:chatVC];

                        } else {
                            QAGroupInviteVC *inviteVC = [[QAGroupInviteVC alloc] init];
                            inviteVC.conversation = group;
                            inviteVC.showType = MPGroupInviteType_QrCode;
                            [weakSelf.navigationController pushViewController:inviteVC animated:YES];
                        }

//                        [QAConversation gerFriendArrayWithGroupID:group Block:^(QAConversation *getFriBGroup, NSNumber *errcode, NSError *error) {
//                            if (![[QAIMDatabase sharedInstance]insertConversation:getFriBGroup]) {
//                                [[QAIMDatabase sharedInstance]updateGroup:getFriBGroup];
//                            }
//
//                            if ([group.userIdList containsObject:myUserInfo.userId]) {
//                                QAChatViewController *chatVC = [[QAChatViewController alloc]init];
//                                chatVC.conversation = getFriBGroup;
//
//                                [weakSelf.navigationController pushViewController:chatVC animated:YES];
//                            } else {
//                                QAGroupInviteVC *inviteVC = [[QAGroupInviteVC alloc] init];
//                                inviteVC.conversation = getFriBGroup;
//                                inviteVC.showType = MPGroupInviteType_QrCode;
//
//                                [weakSelf.navigationController pushViewController:inviteVC animated:YES];
//                            }
//                        }];
                    } else if ([jumpUrlStr containsString:@"subscription/hqr"]) {
                        QAFriendModel *friend = [[QAIMDatabase sharedInstance]getUserWithId:[[dic objectForKey:@"id"] integerValue]];
                        
                        if (!friend) {
                            friend  = [QAFriendModel new];
                            friend.friendID = [[dic objectForKey:@"id"] integerValue];
                        }
                        
                        QAAddressBookDetailVC *userDetailVC = [QAAddressBookDetailVC new];
                        userDetailVC.model = friend;
                        userDetailVC.comeType = MPAddressDetailViewType_QRCode;
                        [self.navigationController pushViewController:userDetailVC animated:YES];
                        
                    }
                }] makeFailureHandler:^(QAResponseModel *response) {
                    WCIToast.showMsg(response.msg);
                }] POST];
                
            }
        }
        
        if (resultArr.count <= 0) {
            QAWebViewController *webVC = [[QAWebViewController alloc]initWithUrl:url.absoluteString];
            webVC.showClose = YES;
            [self.navigationController pushViewController:webVC animated:YES];
        }
    } else {
        QAWebViewController *webVC = [[QAWebViewController alloc]initWithUrl:url.absoluteString];
        webVC.showClose = YES;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

#pragma mark - 定位到聊天位置

- (void)jumpToMsg:(QAMessage *)topMsg{
    [QAModuleService MOChatViewControllerWithjumpMsg:topMsg];
}

#pragma mark 查看所有图片

- (void)lookAllImgButtonAction {
    [self.sheetView hide];
    if (currentWidth < currentHeight) {
        [self lookAllImgButtonActionGo];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(lookAllImgButtonActionGo) withObject:nil afterDelay:0.5];
    }
}
- (void)lookAllImgButtonActionGo{
    QAMessage * model = self.msgArray[self.currentImageIndex];
    if (model.contentType == MPMessageContentTypeVideo) {
        MOLYPicAVPlayerCollectionViewCell *cell = (MOLYPicAVPlayerCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentImageIndex inSection:0]];
        [cell stopAndStartPlayer];
    }

    QALookPhotoVC *vc = [[QALookPhotoVC alloc] init];
    QAChatViewController *chatVc = (QAChatViewController *)self.comeController;
    vc.conversation = chatVc.conversation;
    [QAModuleService pushToChatVc:chatVc];
}
- (void)destroyImage {
    NSLog(@"destroy image");
    [_timerCountDown invalidate];
    _timerCountDown = nil;
    [self.sheetView hide];
    [self popSecure];
}

- (void)timerAction {
    NSInteger count =[self.countDown integerValue];
    if ( count <= 0) {
        [_timerCountDown invalidate];
        _timerCountDown = nil;
        [self destroyImage];
        return;
    }
    count --;
    
    [_progressView setProgress:(float)count/[self.totleCountDown doubleValue]];
    self.countDown = [NSString stringWithFormat:@"%ld",count];
    _labCountDown.text = [self configBurnTimeShowWithCountDownTime:[NSString stringWithFormat:@"%@",self.countDown]];
    
}

#pragma mark - gestureRecognizer

- (void)imageLongPress:(UILongPressGestureRecognizer *)longPress {

    NSLog(@"long press !");
    if (longPress.state == UIGestureRecognizerStateBegan) {
        
        if (self.msgArray.count > 0 && [self.msgArray[0] isKindOfClass:[MOAlbumDetailItemModel class]]) {
            MOAlbumDetailItemModel *model = self.msgArray[_currentImageIndex];
            if (!model.browserType) {//相册长按
                BOOL canShow = NO;
                id content;
                if (model.type == MOSecretAlbumItemTypePic&&self.currentImage) {
                    canShow = YES;
                    content = _currentImage;
                }
                
                if (model.type == MOSecretAlbumItemTypeVid) {
                    NSString *path = [[ICVideoManager shareManager] videoPathForMP4:model.src];
                    BOOL isExist = [ICFileTool fileExistsAtPath:[[NSURL fileURLWithPath:path] path]];
                    canShow = isExist;
                    content = path;
                }
                
                if (canShow &&_longPressDelegate &&
                    [_longPressDelegate respondsToSelector:@selector(mo_pictureBrowseDidLongPressAtIndex:withData:content:)]) {
                    [_longPressDelegate mo_pictureBrowseDidLongPressAtIndex:_currentImageIndex  withData:self.msgArray[_currentImageIndex] content:content];
                }
                
                if (canShow && _moBrowseLongPressBlock) {
                    _moBrowseLongPressBlock(self.msgArray[_currentImageIndex],content,_currentImageIndex);
                }
                
                return;
            }
        }
        
        if (self.currentImage) {
            [self showPopUpView];
        }
    }
}

#pragma mark - notification -recall

- (void)noti_bothRecallMsg:(NSNotification *)noti {
    WeakSelf(ws);
    dispatch_async(dispatch_get_main_queue(), ^{

        id tempData = weakSelf.msgArray[weakSelf.currentImageIndex];
        if ([tempData isKindOfClass:[QAMessage class]]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                QAMessage *msg = (QAMessage *)tempData;
                if ([msg.msgTo isEqualToString:noti.object]) {
                    UICollectionViewCell *cell = [weakSelf.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:weakSelf.currentImageIndex inSection:0]];
                    if ([cell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
                        [((MOLYPicAVPlayerCollectionViewCell *)cell) stopPlayer];
                    }
                    if (weakSelf.timerCountDown) {
                        [weakSelf.timerCountDown invalidate];
                        weakSelf.timerCountDown = nil;
                    }
                    [weakSelf popSecure];
                }
            });
        }
    });
}

-(void)recallMsg:(NSNotification *)noti {
    WeakSelf(ws);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *dict = noti.object;
        NSInteger notiMsgServerId = [dict[@"serverMsgId"] integerValue];
        id tempData = weakSelf.msgArray[weakSelf.currentImageIndex];
        if ([tempData isKindOfClass:[QAMessage class]]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                QAMessage *msg = (QAMessage *)tempData;
                if (msg.serverMsgId == notiMsgServerId) {
                    UICollectionViewCell *cell = [weakSelf.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:weakSelf.currentImageIndex inSection:0]];
                    if ([cell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
                        [((MOLYPicAVPlayerCollectionViewCell *)cell) stopPlayer];
                    }
                    
                    [MOAlerter alertWithTitle:(@"消息已被撤回") message:nil leftTitle:nil leftAction:nil rightTitle:(@"知道了") rightAction:^(MOAlerter *alerter) {
                        
                        if (weakSelf.timerCountDown) {
                            [weakSelf.timerCountDown invalidate];
                            weakSelf.timerCountDown = nil;
                        }
                        [weakSelf popSecure];
                    } touchHide:0];
                }
            });
        }
    });
}

- (void)startVideoPlay:(NSNotification *)noti {
    //开始播放
    [self allowAllDirection];
    id tempCell = [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentImageIndex inSection:0]];
    if ([tempCell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
        MOLYPicAVPlayerCollectionViewCell *cell = (MOLYPicAVPlayerCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentImageIndex inSection:0]];
        if (cell.pauseButton.isSelected) {
            [cell startPlayer];
        }
    }
}

- (void)pauseVideoPlay:(NSNotification *)noti {
    //暂停播放
    [self  becomePortrait];
    if (self.currentVideoCell) {
        if (self.currentVideoCell.task) {
            [self.currentVideoCell.task cancel];
        }
    }

       id tempCell = [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentImageIndex inSection:0]];
       if ([tempCell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
           MOLYPicAVPlayerCollectionViewCell *cell = (MOLYPicAVPlayerCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentImageIndex inSection:0]];
           if (cell.pauseButton.isSelected) {
               [cell stopPlayer];
           }
       }
}

- (void)pauseAndStart{
    if (self.currentVideoCell) {
        [self.currentVideoCell stopAndStartPlayer];
    }
}

//旋转后暂停
- (void)pauseAndStartRound{
    if (self.currentVideoCell) {
        if (self.currentVideoCell.task) {
            [self.currentVideoCell.task cancel];
        }
    }
    id tempCell = [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentImageIndex inSection:0]];
    if ([tempCell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
        MOLYPicAVPlayerCollectionViewCell *cell = (MOLYPicAVPlayerCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentImageIndex inSection:0]];
        [cell stopAndStartPlayer];
    }
}

#pragma mark - Setter and getter

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        _flowLayout = [UICollectionViewFlowLayout new];
        _flowLayout.minimumLineSpacing = 0;
        // 布局方式改为从上至下，默认从左到右
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        // Section Inset就是某个section中cell的边界范围
        _flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        // 每行内部cell item的间距
        _flowLayout.minimumInteritemSpacing = 0;
        CGSize size = CGSizeMake(currentWidth+50, currentHeight);
        _flowLayout.itemSize = size;
        
        _collectionView = [[MOVideoCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
//        _collectionView.delaysContentTouches = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundView = nil;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[LYPictureBrowserCell class] forCellWithReuseIdentifier:NSStringFromClass([LYPictureBrowserCell class])];
        [_collectionView registerClass:[MOLYPicAVPlayerCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MOLYPicAVPlayerCollectionViewCell class])];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class])];
  
    }
    return _collectionView;
}
- (UIImageView *)imgView{
    if (!_imgView) {
        _imgView = [[UIImageView alloc] init];
        _imgView.contentMode = UIViewContentModeScaleAspectFit;
        _imgView.clipsToBounds = YES;
        ViewRadius(_imgView, 8);
        [self.gestureView addSubview:_imgView];
    }
    return _imgView;
}


- (UILongPressGestureRecognizer *)longPress {
    if (!_longPress) {
        _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageLongPress:)];
        _longPress.minimumPressDuration = 0.5; //定义按的时间
        
    }
    return _longPress;
}


- (UITapGestureRecognizer *)doubleTap
{
    if (!_doubleTap) {
        _doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        _doubleTap.numberOfTapsRequired = 2;
        //        _doubleTap.numberOfTouchesRequired = 1;
    }
    return _doubleTap;
}

#pragma mark - 旋转

- (void)statusBarOrientationChange:(NSNotification *)notification

{
    self.directionChange = YES;
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (orientation == UIInterfaceOrientationLandscapeRight||orientation ==UIInterfaceOrientationLandscapeLeft) // home键靠右
    {
        currentWidth = MAX(IPHONE_W, IPHONE_H);
        currentHeight = MIN(IPHONE_W, IPHONE_H);
        [self moment];

    }else{
        
        currentWidth = MIN(IPHONE_W, IPHONE_H);
        currentHeight = MAX(IPHONE_W, IPHONE_H);
        [self moment];
    }
}
- (void)moment{
       self.flowLayout.itemSize = CGSizeMake(currentWidth+50,currentHeight);
       self.collectionView.collectionViewLayout = self.flowLayout;
       self.collectionView.contentOffset = CGPointMake(self.currentImageIndex*(currentWidth+50), 0);
       self.animatedTransition.transitionParameter.transitionImgIndex = self.currentImageIndex;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //指定对应图片
    self.collectionView.contentOffset = CGPointMake(self.currentImageIndex*(currentWidth+50), 0);
    return self.dataSouceArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (currentWidth < currentHeight) {
        id tempData = self.msgArray[indexPath.row];
          if ([tempData isKindOfClass:[QAMessage class]]) {
            QAMessage * model = (QAMessage *)tempData;
              NSInteger replyType = 0;
              if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
                  MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
                  replyType = replyModel.sendType;
              }
              
              if (model.contentType == MPMessageContentTypeVideo || replyType == MPMessageContentTypeVideo) {
                  MOLYPicAVPlayerCollectionViewCell *videocell = (MOLYPicAVPlayerCollectionViewCell *)cell;
                  if ([cell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
                      self.currentVideoCell = videocell;
                      [videocell stopAndStartPlayer];
                  }
            }
          }else{
            MOAlbumDetailItemModel * model = (MOAlbumDetailItemModel *)tempData;
            if (model.type == MOSecretAlbumItemTypeVid) {
                MOLYPicAVPlayerCollectionViewCell *videocell = (MOLYPicAVPlayerCollectionViewCell *)cell;
                if ([cell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
                self.currentVideoCell = videocell;
                [videocell stopAndStartPlayer];
                }
            }
        }
    }
    if (self.directionChange) {
        
    }else{
      id tempData = self.msgArray[indexPath.row];
      if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage * model = (QAMessage *)tempData;
          NSInteger replyType = 0;
          if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
              MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
              replyType = replyModel.sendType;
          }

        if (model.contentType == MPMessageContentTypeVideo || replyType == MPMessageContentTypeVideo) {
            MOLYPicAVPlayerCollectionViewCell *videocell = (MOLYPicAVPlayerCollectionViewCell *)cell;
            if ([cell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
            self.currentVideoCell = videocell;
            [videocell stopAndStartPlayer];
            }
        }
      }else{
        MOAlbumDetailItemModel * model = (MOAlbumDetailItemModel *)tempData;
        if (model.type == MOSecretAlbumItemTypeVid) {
            MOLYPicAVPlayerCollectionViewCell *videocell = (MOLYPicAVPlayerCollectionViewCell *)cell;
            if ([cell isKindOfClass:[MOLYPicAVPlayerCollectionViewCell class]]) {
            self.currentVideoCell = videocell;
            [videocell stopAndStartPlayer];
            }
        }
    }
    }
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    id tempData = self.msgArray[indexPath.row];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *model = (QAMessage *)self.msgArray[indexPath.row];
        if (model.msgBeRead == 1 &&[model.msgFrom integerValue] != [WCICache.user.userId integerValue]) {
            [QAIMService addMsgToBeReadWithMsgServerID:model.serverMsgId andGroupID:model.msgTo];
            model.msgBeRead = 0;
        }
    }
    if (self.directionChange) {
        
    }else{
        id tempData = self.msgArray[indexPath.row];
        if ([tempData isKindOfClass:[QAMessage class]]) {
            QAMessage * model = (QAMessage *)tempData;
            NSInteger replyType = 0;
            if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
                replyType = replyModel.sendType;
            }
            
            if (model.contentType == MPMessageContentTypeVideo || replyType == MPMessageContentTypeVideo) {
                if (!self.isDirectVedio) {
                    MOLYPicAVPlayerCollectionViewCell *videocell = (MOLYPicAVPlayerCollectionViewCell *)cell;
                    self.currentVideoCell = videocell;
                    [videocell stopAndStartPlayer];
                } else {
                    self.isDirectVedio = NO;
                }
            }
        }else{
            MOAlbumDetailItemModel * model = (MOAlbumDetailItemModel *)tempData;
            if (model.type == MOSecretAlbumItemTypeVid) {
                if (!self.isDirectVedio) {
                    MOLYPicAVPlayerCollectionViewCell *videocell = (MOLYPicAVPlayerCollectionViewCell *)cell;
                    self.currentVideoCell = videocell;
                    [videocell stopAndStartPlayer];
                }else{
                    self.isDirectVedio = NO;
                }
            }
        }
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     
    id tempData = self.msgArray[indexPath.row];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *model = (QAMessage *)self.msgArray[indexPath.row];
        NSInteger replyMsgType = 0;
        if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
            replyMsgType = replyModel.sendType;
        }

        if (model.contentType == MPMessageContentTypePicture || model.contentType == MPMessageContentTypeNewPicture || replyMsgType == MPMessageContentTypeNewPicture) {
            LYPictureBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LYPictureBrowserCell class]) forIndexPath:indexPath];
                WeakSelf(ws);

                cell.delegate = self;
                cell.cellIndex = indexPath.row;
                cell.callBackToLoadImageEnd = ^(UIImage *img, NSInteger curIdx) {
                    weakSelf.currentImage = img;

                    if ([weakSelf.totleCountDown integerValue] > 0 || ([model.clearTime integerValue] > 0 && weakSelf.centerCellIndex == curIdx)) {
                        MPParserImageMsg *picMsgModel = [MPParserImageMsg yy_modelWithJSON:model.receiveMsg];
                        NSString *msgUrl = model.receiveMsg;
                        if (picMsgModel) {
                            msgUrl = picMsgModel.url;
                        }
                        if (model.clearStart <= 0 && [model.clearTime integerValue] > 0) {
                            model.clearStart = ServerTime;
                            [[QAIMDatabase sharedInstance] updateClearStarWihtMsg:model];
                        }
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"ImgtimerClearStart" object:model];
                    }
                    
                };
                
                [cell showWithModel:self.dataSouceArray[indexPath.row]];

            return cell;
        } else {
            WeakSelf(ws);
            MOLYPicAVPlayerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([MOLYPicAVPlayerCollectionViewCell class]) forIndexPath:indexPath];
            cell.indexPath = indexPath;
            cell.directionChange = self.directionChange;
            cell.isDirectVideo = self.isDirectVedio;
            if (replyMsgType == 1004) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
                cell.videoInfo = [NSDictionary dictionaryWithJsonString:replyModel.sendContent];
                NSDictionary *dicSendContent = [NSDictionary dictionaryWithJsonString:replyModel.sendContent];
                NSString *path = [[ICVideoManager shareManager] videoPathForMP4:[dicSendContent objectForKey:@"videoPath"]];
                self.currentVideoCell = cell;
                [cell addPlayerURL:[NSURL fileURLWithPath:path] andOriPath:[dicSendContent objectForKey:@"videoPath"]];
            } else {
                cell.videoInfo = model.yy_modelToJSONObject;
                NSString *path = [[ICVideoManager shareManager] videoPathForMP4:model.fileKey];
                self.currentVideoCell = cell;
                [cell addPlayerURL:[NSURL fileURLWithPath:path] andOriPath:model.fileKey];
            }
            
            cell.playBlock = ^(id cell) {
                weakSelf.currentVideoCell = cell;
            };
            cell.dismissBlock = ^{
                [weakSelf popSecure];
            };
            return cell;
        }

    }else{
            MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)self.msgArray[indexPath.row];
            if (model.type == MOSecretAlbumItemTypePic) {
                LYPictureBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LYPictureBrowserCell class]) forIndexPath:indexPath];
                    WeakSelf(ws);
        //            __weak __typeof(&*cell)weakCell = cell;
                    
                    cell.delegate = self;
                    cell.cellIndex = indexPath.row;
                    
                    cell.callBackToLoadImageEnd = ^(UIImage *img, NSInteger curIdx) {
                        weakSelf.currentImage = img;
                //        weakSelf.currentImageIndex = curIdx;
                    };
                    
                    [cell showWithModel:self.dataSouceArray[indexPath.row]];

                    return cell;
            }else{
                /** 视频cell */
                WeakSelf(ws);
                MOLYPicAVPlayerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([MOLYPicAVPlayerCollectionViewCell class]) forIndexPath:indexPath];
                NSString *path = [[ICVideoManager shareManager] videoPathForMP4:model.src];
                cell.directionChange = self.directionChange;
                cell.isDirectVideo = self.isDirectVedio;
                cell.albumModel = model;
                cell.indexPath = indexPath;
                [cell addPlayerURL:[NSURL fileURLWithPath:path] andOriPath:model.src];
                self.currentVideoCell = cell;
                cell.dismissBlock = ^{
                    [weakSelf popSecure];
                };
                cell.playBlock = ^(id cell) {
                    weakSelf.currentVideoCell = cell;
                };
                return cell;
            }
    }
}

#pragma mark - LFPhotoEditingControllerDelegate

- (void)lf_PhotoEditingController:(LFPhotoEditingController *)photoEditingVC didCancelPhotoEdit:(LFPhotoEdit *)photoEdit {
    if (currentWidth<currentHeight) {
        [self porPopNoAnimate];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(porPopNoAnimate) withObject:nil afterDelay:0.5];
    }
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)lf_PhotoEditingController:(LFPhotoEditingController *)photoEditingVC didFinishPhotoEdit:(LFPhotoEdit *)photoEdit {
    if (currentWidth<currentHeight) {
        [self porPopNoAnimate];
    }else{
        [self becomePortrait];
        [self performSelector:@selector(porPopNoAnimate) withObject:nil afterDelay:0.5];
    }
    [self.navigationController setNavigationBarHidden:YES];
    
    if (photoEdit) {
       
    }
}

#pragma mark - System Delegate scroll view



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    
    CGFloat offset = _collectionView.contentOffset.x;
    NSInteger cellIndex = offset/(currentWidth+50);
//    if (UIDeviceOrientationIsLandscape(self.orientation)) {
//        cellIndex = offset/(_collectionView.width);
//    }
//    if (self.currentImageIndex != cellIndex) {
//         self.directionChange = NO;
//    }
    self.centerCellIndex = cellIndex;
    self.currentImageIndex = cellIndex;
    self.animatedTransition.transitionParameter.transitionImgIndex = self.currentImageIndex;
    [self setupBaseViewControllerProperty:cellIndex];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.directionChange = NO;
}
#pragma mark - Custom Delegate
- (void)imageViewClick:(NSInteger)cellIndex{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Event

- (void)interactiveTransitionRecognizerAction:(UIPanGestureRecognizer *)gestureRecognizer
{
    if (self.animating) {
        return;
    }
    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view];
    
    CGFloat scale = 1 - (translation.y / SCREENHEIGHT);
    scale = scale < 0 ? 0 : scale;
    scale = scale > 1 ? 1 : scale;
    id tempData = self.msgArray[_currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
//            QAMessage *model = (QAMessage *)tempData;
            self.navigationController.navigationBar.alpha = scale;
            switch (gestureRecognizer.state) {
                case UIGestureRecognizerStatePossible:
                    NSLog(@"---------------UIGestureRecognizerStatePossible------%ld----------------",(UIGestureRecognizerState)gestureRecognizer.state);

                    break;
                case UIGestureRecognizerStateBegan:{
                    NSLog(@"---------------触摸手势开始------%ld----------------",(UIGestureRecognizerState)gestureRecognizer.state);

                    CGPoint velocity = [gestureRecognizer velocityInView:gestureRecognizer.view];
                    if (velocity.y > 0 && (currentWidth<currentHeight)) {
                        NSLog(@" > 0");
                    } else {
                        NSLog(@" < 0");
                        return;
                    }

                    [self setupBaseViewControllerProperty:self.animatedTransition.transitionParameter.transitionImgIndex];
//                    self.animatedTransition.percentIntractive.isInteractive = YES;

                    self.collectionView.hidden = YES;
                    self.imgView.hidden = NO;
                    
                    self.animatedTransition.transitionParameter.gestureRecognizer = gestureRecognizer;
                    self.navigationController.delegate = self.animatedTransition;
                    [self popSecure];
        //            [self dismissViewControllerAnimated:YES completion:nil];
                    
                }
                    break;
                case UIGestureRecognizerStateChanged: {
//                    NSLog(@"---------------UIGestureRecognizerStateChanged-%ld----------------",(UIGestureRecognizerState)gestureRecognizer.state);
                    _imgView.center = CGPointMake(self.transitionImgViewCenter.x + translation.x * scale, self.transitionImgViewCenter.y + translation.y);
                    _imgView.transform = CGAffineTransformMakeScale(scale, scale);
                    
                }
                    break;

                case UIGestureRecognizerStateFailed:
                case UIGestureRecognizerStateCancelled:
                case UIGestureRecognizerStateEnded: {
                    self.animating = YES;

                    if (scale > 0.85f) {
                        [UIView animateWithDuration:0.2 animations:^{
                            self.imgView.center = self.transitionImgViewCenter;
                            _imgView.transform = CGAffineTransformMakeScale(1, 1);
                            
                        } completion:^(BOOL finished) {
                            _imgView.transform = CGAffineTransformIdentity;
                            NSLog(@"--------------------------触摸手势动画结束");
                            self.animating = NO;
                        }];
                        NSLog(@"---------------触摸手势取消------%ld----------------",(UIGestureRecognizerState)gestureRecognizer.state);
                        self.collectionView.hidden = NO;
                        self.imgView.hidden = YES;
                    }else{
                        NSLog(@"---------------触摸手势结束------%ld----------------",(UIGestureRecognizerState)gestureRecognizer.state);
                        self.animating = NO;
                    }
                    self.animatedTransition.transitionParameter.transitionImage = _imgView.image;
                    self.animatedTransition.transitionParameter.currentPanGestImgFrame = _imgView.frame;
                    
                    self.animatedTransition.transitionParameter.gestureRecognizer = nil;
                    self.navigationController.delegate = nil;

                }
            }
    } else {
            MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)tempData;
            self.navigationController.navigationBar.alpha = scale;
            switch (gestureRecognizer.state) {
                case UIGestureRecognizerStatePossible:
                    break;
                case UIGestureRecognizerStateBegan:{
                    CGPoint velocity = [gestureRecognizer velocityInView:gestureRecognizer.view];
//                     && model.type == MOSecretAlbumItemTypePic
                    if (velocity.y > 0 && (currentWidth<currentHeight)) {
                        NSLog(@" > 0");
                        
                    } else {
                        NSLog(@" < 0");
                        return;
                    }
                    
                        [self setupBaseViewControllerProperty:self.animatedTransition.transitionParameter.transitionImgIndex];
                       self.collectionView.hidden = YES;
                       self.imgView.hidden = NO;
                       
                       self.animatedTransition.transitionParameter.gestureRecognizer = gestureRecognizer;
                       self.navigationController.delegate = self.animatedTransition;
                       if (model.browserType == MOAlbumBrowserTypeFile||model.browserType == MOAlbumBrowserTypeFileCollection) {
                           [self popToIntoVC];
                       }else{
                           [self popSecure];
                       }
    
                }
                    break;
                case UIGestureRecognizerStateChanged: {
                    
                    _imgView.center = CGPointMake(self.transitionImgViewCenter.x + translation.x * scale, self.transitionImgViewCenter.y + translation.y);
                    _imgView.transform = CGAffineTransformMakeScale(scale, scale);
                    
                }
                    break;

                case UIGestureRecognizerStateFailed:
                case UIGestureRecognizerStateCancelled:
                case UIGestureRecognizerStateEnded: {
                    [self endGestureWithScale:scale];
                }
            }
    }
    
}

- (void)endGestureWithScale:(CGFloat)scale {
    if (scale > 0.85f) {
        [UIView animateWithDuration:0.2 animations:^{
            self.imgView.center = self.transitionImgViewCenter;
            _imgView.transform = CGAffineTransformMakeScale(1, 1);
            
        } completion:^(BOOL finished) {
            _imgView.transform = CGAffineTransformIdentity;
        }];
//                        NSLog(@"secondevc取消");
        self.collectionView.hidden = NO;
        self.imgView.hidden = YES;
    }else{
    }
    self.animatedTransition.transitionParameter.transitionImage = _imgView.image;
    self.animatedTransition.transitionParameter.currentPanGestImgFrame = _imgView.frame;
    
    self.animatedTransition.transitionParameter.gestureRecognizer = nil;
    self.navigationController.delegate = nil;
}

#pragma mark - Private Method

- (void)setupBaseViewControllerProperty:(NSInteger)cellIndex {
    
    id tempData = self.msgArray[cellIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        
        QAMessage *model = (QAMessage *)tempData;
        NSInteger replyType = 0;
        if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
            replyType = replyModel.sendType;
        }

        if (model.contentType == MPMessageContentTypePicture || model.contentType == MPMessageContentTypeNewPicture || replyType == MPMessageContentTypeNewPicture) {
                id tempCell = [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
            if ([tempCell isKindOfClass:[LYPictureBrowserCell class]]) {
                LYPictureBrowserCell *cell = (LYPictureBrowserCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
                
                self.animatedTransition.transitionParameter.transitionImage = cell.pictureImageScrollView.zoomImageView.image;
                self.animatedTransition.transitionParameter.transitionImgIndex = cellIndex;
                
                self.imgView.frame = cell.pictureImageScrollView.zoomImageView.frame;
                self.imgView.image = cell.pictureImageScrollView.zoomImageView.image;
                self.imgView.hidden = YES;
                self.transitionImgViewCenter = _imgView.center;
                
                [cell showWithModel:self.dataSouceArray[cellIndex]];

                WeakSelf(ws);
                __weak __typeof(&*cell)weakCell = cell;
                cell.callBackToLoadImageEnd = ^(UIImage *img, NSInteger curIdx) {
                    weakSelf.currentImage = img;
                    weakSelf.currentImageIndex = weakCell.cellIndex;
                    if (model.clearStart <= 0 && [model.clearTime integerValue] > 0) {
                        model.clearStart = ServerTime;
                        [[QAIMDatabase sharedInstance] updateClearStarWihtMsg:model];
                    }
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ImgtimerClearStart" object:model];
                };
            }
        } else{
              MOLYPicAVPlayerCollectionViewCell *cell = (MOLYPicAVPlayerCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
            
              NSDictionary *dicMsg = [NSDictionary dictionaryWithJsonString:model.receiveMsg];
            if (replyType == 1004) {
                MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
                dicMsg = [NSDictionary dictionaryWithJsonString:replyModel.sendContent];
            }
              UIImage *videoArrowImage;
        
              if ([dicMsg.allKeys containsObject:@"localSnapshot"]) {
                  NSString * name = [[[dicMsg objectForKey:@"localSnapshot"] lastPathComponent] stringByDeletingPathExtension];
                  videoArrowImage = [[ICMediaManager sharedManager] videoImageWithFileName:[NSString stringWithFormat:@"%@.jpg",name]];//取图片
              } else {
                  
                  NSString *urlPath = [dicMsg objectForKey:@"videoPath"];
                  NSString *path = [[ICVideoManager shareManager] receiveVideoPathWithFileKey:[urlPath.lastPathComponent stringByDeletingPathExtension]];
                  videoArrowImage = [[ICMediaManager sharedManager] videoConverPhotoWithVideoPath:path
                                                                                                      size:CGSizeZero
                                                                                                  snapShot:[dicMsg objectForKey:@"snapshot"]
                                                                                                  isSender:NO];

              }
              self.animatedTransition.transitionParameter.transitionImage = videoArrowImage;
              self.animatedTransition.transitionParameter.transitionImgIndex = cellIndex;
              self.imgView.frame = cell.videoView.frame;
              self.imgView.image = videoArrowImage;
              self.imgView.hidden = YES;
              self.transitionImgViewCenter = _imgView.center;
        }
    } else{
      MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)tempData;
      if (model.type == MOSecretAlbumItemTypePic) {
        id tempCell = [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
        if ([tempCell isKindOfClass:[LYPictureBrowserCell class]]) {
              LYPictureBrowserCell *cell = (LYPictureBrowserCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
              
              self.animatedTransition.transitionParameter.transitionImage = cell.pictureImageScrollView.zoomImageView.image;
              self.animatedTransition.transitionParameter.transitionImgIndex = cellIndex;
              
              self.imgView.frame = cell.pictureImageScrollView.zoomImageView.frame;
              self.imgView.image = cell.pictureImageScrollView.zoomImageView.image;
              self.imgView.hidden = YES;
              self.transitionImgViewCenter = _imgView.center;
              
              [cell showWithModel:self.dataSouceArray[cellIndex]];

              WeakSelf(ws);
              __weak __typeof(&*cell)weakCell = cell;
              cell.callBackToLoadImageEnd = ^(UIImage *img, NSInteger curIdx) {
                  weakSelf.currentImage = img;
                  weakSelf.currentImageIndex = weakCell.cellIndex;
              };
              //    self.currentImage = cell.pictureImageScrollView.zoomImageView.image;
              //    _currentImageIndex = cell.cellIndex;
        }
      }else{
            ICMediaManager *manager  = [ICMediaManager sharedManager];
            MOLYPicAVPlayerCollectionViewCell *cell = (MOLYPicAVPlayerCollectionViewCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:cellIndex inSection:0]];
          
            NSString *path;
            UIImage *videoArrowImage;
      
            path = [[ICVideoManager shareManager] receiveVideoPathWithFileKey:[model.src.lastPathComponent stringByDeletingPathExtension]];
            videoArrowImage = [manager getVideoConverVideoPath:path size:CGSizeMake(0, 0)];
                
           self.animatedTransition.transitionParameter.transitionImage = videoArrowImage;
           self.animatedTransition.transitionParameter.transitionImgIndex = cellIndex;
          self.imgView.frame = cell.videoView?cell.videoView.frame:self.collectionView.frame;
          self.imgView.image = videoArrowImage?videoArrowImage:_currentImage;
           self.imgView.hidden = YES;
           self.transitionImgViewCenter = self.imgView.center;
        }
    }
}


- (void)handleDoubleTap:(UITapGestureRecognizer *)recognizer {
    id tempData = self.msgArray[_currentImageIndex];
    if ([tempData isKindOfClass:[QAMessage class]]) {
        QAMessage *model = (QAMessage *)self.msgArray[_currentImageIndex];
        BOOL isImage = NO;
        if (model.contentType == MPMessageContentTypeNewReply || model.contentType == MPMessageContentTypeSingleReply) {
            MPParserReplyMsg *replyModel = [MPParserReplyMsg yy_modelWithJSON:model.receiveMsg];
            if (replyModel.sendType == 1022) {
                isImage = YES;
            }
        }

        if (model.contentType == MPMessageContentTypePicture || model.contentType == MPMessageContentTypeNewPicture || isImage) {
            CGPoint touchPoint = [recognizer locationInView:self.collectionView];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:touchPoint];
            LYPictureBrowserCell *cell = (LYPictureBrowserCell *)[_collectionView cellForItemAtIndexPath:indexPath];
            
            if (cell.pictureImageScrollView.zoomScale <= 1.0) {
                CGFloat scaleX = touchPoint.x-(self.currentImageIndex*(currentWidth+50)) + cell.pictureImageScrollView.contentOffset.x;//需要放大的图片的X点
                CGFloat sacleY = touchPoint.y+ cell.pictureImageScrollView.contentOffset.y;//需要放大的图片的Y点
                CGRect rect = CGRectMake(scaleX, sacleY, 10, 10);
                
                [cell.pictureImageScrollView zoomToRect:rect animated:YES];
            } else {
                [cell.pictureImageScrollView setZoomScale:1.0 animated:YES]; //还原
            }
        }
    }else{
        MOAlbumDetailItemModel *model = (MOAlbumDetailItemModel *)self.msgArray[_currentImageIndex];
        if (model.type ==  MOSecretAlbumItemTypePic) {
            CGPoint touchPoint = [recognizer locationInView:self.collectionView];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:touchPoint];
            LYPictureBrowserCell *cell = (LYPictureBrowserCell *)[_collectionView cellForItemAtIndexPath:indexPath];
            
            if (cell.pictureImageScrollView.zoomScale <= 1.0) {
                CGFloat scaleX = touchPoint.x-(self.currentImageIndex*(currentWidth+50)) + cell.pictureImageScrollView.contentOffset.x;//需要放大的图片的X点
                CGFloat sacleY = touchPoint.y+ cell.pictureImageScrollView.contentOffset.y;//需要放大的图片的Y点
                CGRect rect = CGRectMake(scaleX, sacleY, 10, 10);
                
                [cell.pictureImageScrollView zoomToRect:rect animated:YES];
            } else {
                [cell.pictureImageScrollView setZoomScale:1.0 animated:YES]; //还原
            }
        }
    }
    
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        WCIToast.showMsg(@"保存失败");
    } else {
        WCIToast.showMsg(@"保存成功");
    }
}


- (NSString *)configBurnTimeShowWithCountDownTime:(NSString *)countDownTime {
    NSString *strShowTime = @"";
    NSInteger countDown = [countDownTime integerValue];
    
    if (countDown >= 0 && countDown <= 300) {
        strShowTime = [NSString stringWithFormat:@"%@s",countDownTime];
    } else if (countDown >= 300 && countDown <= 60 * 60) {
        strShowTime = [NSString stringWithFormat:@"%.0fm",ceil(countDown / 60.0) ];
    } else {
        strShowTime = [NSString stringWithFormat:@"%.0fh",ceil(countDown / 60.0 / 60.0) ];
    }
    

    return strShowTime;
}

@end
